<?php

namespace app\models;

use Yii;
use app\components\BaseActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

/**
 * This is the model class for table "{{%admin_group}}".
 *
 * @property integer $id
 * @property string $gname
 * @property integer $ctime
 * @property string $privilege_ids
 */
class AdminGroup extends BaseActiveRecord {
    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%admin_group}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['gname'], 'required'],
            [['ctime'], 'integer'],
            [['gname'], 'string', 'max' => 100],
            [['privilege_ids'], 'string', 'max' => 500]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'gname' => '角色名称',
            'ctime' => 'Ctime',
            'privilege_ids' => '权限',
        ];
    }

    public static function getGroups() {
        $groups = static::find()->asArray()->all();
        return ArrayHelper::map($groups, 'id', 'gname');
    }

    public function getPrivilegeIds() {
        if (empty($this->privilege_ids)) {
            return [];
        }
        return json_decode($this->privilege_ids);
    }

    public function beforeValidate() {
        if (is_array($this->privilege_ids)) {
            $this->privilege_ids = Json::encode($this->privilege_ids);
        }
        return parent::beforeValidate();
    }

    public function afterSave($insert, $changedAttributes) {
        $name = $this->id . '_admin_menus';
        Yii::$app->cache->delete($name);

        parent::afterSave($insert, $changedAttributes);
    }
}
